<template>
  <div class="user-detail-container">
    <div class="container py-4">
      <!-- 页面标题 -->
      <div class="row mb-4">
        <div class="col">
          <h2 class="mb-0">用户详情</h2>
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
              <li class="breadcrumb-item">
                <a href="#" @click.prevent="$router.push('/user/profile')">个人中心</a>
              </li>
              <li class="breadcrumb-item active" aria-current="page">用户详情</li>
            </ol>
          </nav>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="alert alert-danger" role="alert">
        <h4 class="alert-heading">加载失败!</h4>
        <p>{{ error }}</p>
        <hr>
        <button class="btn btn-outline-danger" @click="fetchData">重新加载</button>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="d-flex justify-content-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <span class="ms-2">正在加载用户数据...</span>
      </div>

      <!-- 主要内容 -->
      <div v-else class="fade-in">
        <!-- 用户基本信息 -->
        <div class="row mb-4">
          <div class="col-lg-8">
            <div class="card shadow-sm h-100">
              <div class="card-body">
                <div class="d-flex flex-column flex-md-row align-items-center">
                  <img 
                    :src="user.avatar || defaultAvatar" 
                    class="rounded-circle mb-3 mb-md-0 me-md-4" 
                    alt="用户头像" 
                    width="120" 
                    height="120"
                    @error="handleImageError"
                  >
                  <div class="flex-grow-1 text-center text-md-start">
                    <h3 class="mb-1">{{ user.username }}</h3>
                    <h5 class="text-muted mb-2">{{ user.nickname || '暂无昵称' }}</h5>
                    <p class="mb-1">
                      <span class="badge bg-primary me-2">学生</span>
                      <span class="badge bg-success">活跃</span>
                    </p>
                    <p class="text-muted mb-2">
                      <i class="bi bi-calendar me-1"></i>
                      加入时间: {{ formatDate(user.createdAt) }}
                    </p>
                    <p class="mb-0 bio-text">简介：{{ user.bio || '这个用户很懒，还没有个人简介' }}</p>
                  </div>
                </div>
                <div class="d-flex justify-content-center justify-content-md-end mt-3">
                  <button 
                    v-if="!isCurrentUser && !isFollowing" 
                    class="btn btn-primary me-2" 
                    @click="followUser"
                  >
                    <i class="bi bi-person-plus me-1"></i> 关注
                  </button>
                  <button 
                    v-else-if="!isCurrentUser" 
                    class="btn btn-outline-secondary me-2" 
                    @click="unfollowUser"
                  >
                    <i class="bi bi-check me-1"></i> 已关注
                  </button>
                  <button 
                    v-if="!isCurrentUser" 
                    class="btn btn-outline-primary"
                    @click="sendMessage"
                  >
                    <i class="bi bi-chat-dots me-1"></i> 私信
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="col-lg-4 mt-4 mt-lg-0">
            <div class="card shadow-sm h-100">
              <div class="card-body">
                <h5 class="card-title">用户统计</h5>
                <div class="row text-center">
                  <div class="col-4">
                    <div class="stat-number">{{ userStats.postsCount || 0 }}</div>
                    <div class="stat-label">帖子</div>
                  </div>
                  <div class="col-4">
                    <div class="stat-number">{{ userStats.likesCount || 0 }}</div>
                    <div class="stat-label">点赞</div>
                  </div>
                  <div class="col-4">
                    <div class="stat-number">{{ userStats.favoritesCount || 0 }}</div>
                    <div class="stat-label">收藏</div>
                  </div>
                </div>
                <hr>
                <h5 class="card-title mt-3">关注关系</h5>
                <div class="row text-center">
                  <div class="col-6">
                    <div class="stat-number">{{ userStats.followingCount || 0 }}</div>
                    <div class="stat-label">关注</div>
                  </div>
                  <div class="col-6">
                    <div class="stat-number">{{ userStats.followersCount || 0 }}</div>
                    <div class="stat-label">粉丝</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户活动 -->
        <div class="row mb-4">
          <div class="col-12">
            <ul class="nav nav-tabs mb-4">
              <li class="nav-item">
                <a 
                  class="nav-link" 
                  :class="{ active: activeTab === 'posts' }" 
                  @click="activeTab = 'posts'" 
                  href="#"
                >
                  发布的帖子
                  <span class="badge bg-primary ms-1">{{ userStats.postsCount }}</span>
                </a>
              </li>
              <li class="nav-item">
                <a 
                  class="nav-link" 
                  :class="{ active: activeTab === 'likes' }" 
                  @click="activeTab = 'likes'" 
                  href="#"
                >
                  点赞的帖子
                  <span class="badge bg-primary ms-1">{{ userStats.likesCount }}</span>
                </a>
              </li>
              <li class="nav-item">
                <a 
                  class="nav-link" 
                  :class="{ active: activeTab === 'favorites' }" 
                  @click="activeTab = 'favorites'" 
                  href="#"
                >
                  收藏的帖子
                  <span class="badge bg-primary ms-1">{{ userStats.favoritesCount }}</span>
                </a>
              </li>
            </ul>

            <!-- 发布的帖子 -->
            <div v-if="activeTab === 'posts'" class="tab-content">
              <div v-if="userPosts.length === 0" class="text-center py-5">
                <i class="bi bi-file-earmark-text fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未发布任何帖子</p>
              </div>
              <div v-else class="row">
                <div 
                  v-for="post in userPosts" 
                  :key="post.id" 
                  class="col-md-6 col-lg-4 mb-4 slide-in"
                >
                  <div class="card h-100 shadow-sm">
                    <img 
                      :src="post.cover || defaultPostCover" 
                      class="card-img-top" 
                      alt="帖子封面"
                      style="height: 150px; object-fit: cover;"
                      @error="handlePostImageError"
                    >
                    <div class="card-body d-flex flex-column">
                      <h5 class="card-title">{{ post.title }}</h5>
                      <p class="card-text flex-grow-1">{{ post.summary || '暂无摘要' }}</p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(post.createdAt) }}</span>
                        <span>{{ post.viewCount || 0 }} 浏览</span>
                      </div>
                      <button 
                        class="btn btn-outline-primary mt-2"
                        @click="goToPost(post.id)"
                      >
                        <i class="bi bi-eye me-1"></i> 查看详情
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 点赞的帖子 -->
            <div v-else-if="activeTab === 'likes'" class="tab-content">
              <div v-if="userLikes.length === 0" class="text-center py-5">
                <i class="bi bi-hand-thumbs-up fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未点赞任何帖子</p>
              </div>
              <div v-else class="row">
                <div 
                  v-for="like in userLikes" 
                  :key="like.id" 
                  class="col-md-6 col-lg-4 mb-4 slide-in"
                >
                  <div class="card h-100 shadow-sm">
                    <img 
                      :src="like.cover || defaultPostCover" 
                      class="card-img-top" 
                      alt="帖子封面"
                      style="height: 150px; object-fit: cover;"
                      @error="handlePostImageError"
                    >
                    <div class="card-body d-flex flex-column">
                      <h5 class="card-title">{{ like.postTitle }}</h5>
                      <p class="card-text flex-grow-1">
                        <small class="text-muted">发布人: {{ like.postAuthor }}</small>
                      </p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(like.createdAt) }}</span>
                        <span>{{ like.views || 0 }} 浏览</span>
                      </div>
                      <button 
                        class="btn btn-outline-primary mt-2"
                        @click="goToPost(like.postId)"
                      >
                        <i class="bi bi-eye me-1"></i> 查看详情
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 收藏的帖子 -->
            <div v-else-if="activeTab === 'favorites'" class="tab-content">
              <div v-if="userFavorites.length === 0" class="text-center py-5">
                <i class="bi bi-star fs-1 text-muted"></i>
                <p class="mt-2 text-muted">该用户暂未收藏任何帖子</p>
              </div>
              <div v-else class="row">
                <div 
                  v-for="favorite in userFavorites" 
                  :key="favorite.id" 
                  class="col-md-6 col-lg-4 mb-4 slide-in"
                >
                  <div class="card h-100 shadow-sm">
                    <img 
                      :src="favorite.cover || defaultPostCover" 
                      class="card-img-top" 
                      alt="帖子封面"
                      style="height: 150px; object-fit: cover;"
                      @error="handlePostImageError"
                    > 
                    <div class="card-body d-flex flex-column">
                      <h5 class="card-title">{{ favorite.postTitle }}</h5>
                      <p class="card-text flex-grow-1">
                        <small class="text-muted">发布人: {{ favorite.postAuthor }}</small>
                      </p>
                      <div class="d-flex justify-content-between text-muted small">
                        <span>{{ formatDate(favorite.createdAt) }}</span>
                        <span>{{ favorite.views || 0 }} 浏览</span>
                      </div>
                      <button 
                        class="btn btn-outline-primary mt-2"
                        @click="goToPost(favorite.postId)"
                      >
                        <i class="bi bi-eye me-1"></i> 查看详情
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
    <BackToTop>
  </BackToTop>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// 默认图片
import defaultAvatar from '@/assets/images/头像加载失败.jpg'
import defaultPostCover from '@/assets/images/封面加载失败.webp'
import BackToTop from '@/components/BackToTop.vue'

import useUserInfoStore from '@/stores/userInfo.js'

import { getUserInfoByIdService, } from '@/api/user.js'

import { getPostDetailService,
        getPostCoverByIdService,
        getPostListNoPageService} from '@/api/post.js'

import { getFollowingListService,
          getFollowerListService,
          FollowService,
          UnfollowService } from '@/api/Follow.js'
          
import { getUserLikesService,
          getUserFavoritesService} from '@/api/LikesFavorites.js'


const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()

// 数据状态
const user = ref({})
const userStats = ref({})
const userPosts = ref([])
const userLikes = ref([])
const userFavorites = ref([])
const isFollowing = ref(false)// 是否已关注
const isCurrentUser = ref(false)// 是否是当前用户
const activeTab = ref('posts')// 默认显示帖子

const loading = ref(true)
const error = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 处理用户头像加载错误
const handleImageError = (event) => {
  event.target.src = defaultAvatar
}

// 处理帖子封面加载错误
const handlePostImageError = (event) => {
  event.target.src = defaultPostCover
}

// 获取用户数据
const fetchData = async () => {
  try {
    loading.value = true
    error.value = null
    
    const userId = route.params.id
    
    const res = await getUserInfoByIdService(userId)
    user.value = res.data
    console.log('获取到的用户数据:', user.value)
    
    // 检查是否是当前用户
    // 确保 userInfoStore.info 存在再进行比较
    isCurrentUser.value = !!(userInfoStore.info && userId == userInfoStore.info.id)
    
    // 如果是当前用户，确保不显示关注按钮
    if (isCurrentUser.value) {
      isFollowing.value = false
    } else {
      // 检查当前用户是否已经关注了该帖子用户
      try {
        const followingList = await getFollowingListService(userInfoStore.info.id)
        console.log('当前用户关注列表:', followingList)
        isFollowing.value = followingList.data.some(item => item.followingId == userId)
      } catch (err) {
        console.error('获取关注列表失败:', err)
        isFollowing.value = false
      }
    }

    // 获取用户帖子数量
    getPostListNoPageService(userId).then(res => {
      userStats.value.postsCount = res.data.length || 0
    }).catch(() => {
      userStats.value.postsCount = 0
    })

    // 获取用户点赞和收藏数量
    getUserLikesService(userId,'like').then(res => {
      userStats.value.likesCount = res.data.length
    }).catch(() => {
      userStats.value.likesCount = 0
    })

    getUserFavoritesService(userId,'favorite').then(res => {
      userStats.value.favoritesCount = res.data.length
    }).catch(() => {
      userStats.value.favoritesCount = 0
    })

    // 获取关注和粉丝数量
    getFollowingListService(userId).then(res => {
      userStats.value.followingCount = res.data.length
    }).catch(() => {
      userStats.value.followingCount = 0
    })

    getFollowerListService(userId).then(res => {
      userStats.value.followersCount = res.data.length
    }).catch(() => {
      userStats.value.followersCount = 0
    })
    // console.log('获取的关注和粉丝数量:', userStats.value)

    // 用户发布帖子数据
    const postsRes = await getPostListNoPageService(userId)
    userPosts.value = postsRes.data || []
    // 通过获取到的postId数组，获取对应的帖子信息
    userPosts.value = await Promise.all(userPosts.value.map(async (userPost) => { 
      const postCoverRes = await getPostCoverByIdService(userPost.id)

      let postCover = defaultPostCover
      if (postCoverRes.data && postCoverRes.data.length > 0) {
        // 如果有封面图片，使用第一张图片
        const firstImage = postCoverRes.data[0]
        postCover = firstImage.imageUrl.startsWith('http') 
          ? firstImage.imageUrl 
          : `http://localhost:8080${firstImage.imageUrl}`
      } else {
        // 如果没有封面图片，尝试处理res.data中的图片数据（与Market.vue中处理方式一致）
        if (userPost.cover) {
          postCover = userPost.cover.startsWith('http') 
            ? userPost.cover 
            : `http://localhost:8080${userPost.cover}`
        }
      }
      
      return {
        ...userPost, 
        cover: postCover,
        summary: userPost.content.length > 10 ? userPost.content.substring(0, 10) + '...' : userPost.content,
      }
    }))
    // console.log('获取的帖子数据:', userPosts.value)
    
    // 用户点赞数据
    const likesRes = await getUserLikesService(userId,'like')
    userLikes.value = likesRes.data || []
    //通过获取到的postId数组，获取对应的帖子信息
    userLikes.value = await Promise.all(userLikes.value.map(async (like) => {
      const postRes = await getPostDetailService(like.postId)
      const postCoverRes = await getPostCoverByIdService(like.postId)
      const userInfo = await getUserInfoByIdService(postRes.data.userId)
      
      console.log('获取的帖子详情数据:', postRes.data)
      const post = postRes.data
      
      // 处理帖子封面图片
      let postCover = defaultPostCover
      if (postCoverRes.data && postCoverRes.data.length > 0) {
        // 如果有封面图片，使用第一张图片
        const firstImage = postCoverRes.data[0]
        postCover = firstImage.imageUrl.startsWith('http') 
          ? firstImage.imageUrl 
          : `http://localhost:8080${firstImage.imageUrl}`
      }
      
      return {
        ...like,
        postTitle: post.title,
        postAuthor: userInfo.data.nickname || userInfo.data.username || '未知用户',
        cover: postCover,
        views: post.viewCount || 0
      }
    }))
    // console.log('获取的点赞数据:', userLikes.value)
    
    // 用户收藏数据
    const favoritesRes = await getUserFavoritesService(userId,'favorite')
    userFavorites.value = favoritesRes.data || []
    // 通过获取到的postId数组，获取对应的帖子信息
    userFavorites.value = await Promise.all(userFavorites.value.map(async (favorite) => {
      const postRes = await getPostDetailService(favorite.postId)
      const postCoverRes = await getPostCoverByIdService(favorite.postId)
      const userInfo = await getUserInfoByIdService(postRes.data.userId)

      const post = postRes.data
      
      // 处理帖子封面图片
      let postCover = defaultPostCover
      if (postCoverRes.data && postCoverRes.data.length > 0) {
        // 如果有封面图片，使用第一张图片
        const firstImage = postCoverRes.data[0]
        postCover = firstImage.imageUrl.startsWith('http') 
          ? firstImage.imageUrl 
          : `http://localhost:8080${firstImage.imageUrl}`
      }
      
      return {
        ...favorite,
        postTitle: post.title,
        postAuthor: userInfo.data.nickname || userInfo.data.username || '未知用户',
        cover: postCover,
        views: post.viewCount || 0
      }
    }))
    // console.log('获取的收藏数据:', userFavorites.value)
    
    // 检查是否已关注该用户
    // 确保 isFollowing 有默认值
    if (isFollowing.value === undefined) {
      isFollowing.value = false
    }
    
  } catch (err) {
    console.error('获取用户数据失败:', err)
    error.value = `获取用户数据失败: ${err.message || '未知错误'}`
    ElMessage.error('获取用户数据失败')
  } finally {
    loading.value = false
  }
}

// 关注用户
const followUser = async () => {
  try {
    await ElMessageBox.confirm('确定要关注该用户吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用关注API
    await FollowService(user.value.id)
    isFollowing.value = true
    userStats.value.followingCount++
    ElMessage.success('已关注用户')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('关注失败:', error)
      ElMessage.error('关注失败: ' + (error.message || '未知错误'))
    }
  }
}

// 取消关注
const unfollowUser = async () => {
  try {
    await ElMessageBox.confirm('确定要取消关注吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用取消关注API
    await UnfollowService(user.value.id)
    isFollowing.value = false
    userStats.value.followingCount--
    ElMessage.success('已取消关注')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消关注失败:', error)
      ElMessage.error('取消关注失败: ' + (error.message || '未知错误'))
    }
  }
}

// 发送私信
const sendMessage = () => {
  ElMessage.info('功能开发中...')
}

// 跳转到帖子详情
const goToPost = (postId) => {
  router.push(`/post/detail/${postId}`)
}

// 初始化数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.user-detail-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 2rem;
}

.fade-in {
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.slide-in {
  animation: slideIn 0.3s ease-out;
  animation-fill-mode: both;
}

@keyframes slideIn {
  from { 
    opacity: 0; 
    transform: translateY(30px);
  }
  to { 
    opacity: 1; 
    transform: translateY(0);
  }
}

.stat-number {
  font-size: 1.5rem;
  font-weight: bold;
  color: #0d6efd;
}

.stat-label {
  font-size: 0.875rem;
  color: #6c757d;
}

.bio-text {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card {
  transition: all 0.3s ease;
  border: none;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.nav-tabs .nav-link {
  cursor: pointer;
  border: none;
  background-color: transparent;
  transition: all 0.3s ease;
}

.nav-tabs .nav-link:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.nav-tabs .nav-link.active {
  border-bottom: 2px solid #0d6efd;
  font-weight: 500;
}

.breadcrumb {
  background-color: transparent;
  padding: 0;
}

.breadcrumb-item a {
  text-decoration: none;
  color: #6c757d;
  transition: color 0.2s ease;
}

.breadcrumb-item a:hover {
  color: #0d6efd;
}

.breadcrumb-item.active {
  color: #495057;
}

.spinner-border {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>